﻿// SDMX Artefact Standalone Editor (SAE). An SDMX 2.0 Editor.
//    Copyright (C) 2009  Philippe Prati
//
//    This program is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 2 of the License, or
//    (at your option) any later version.
//
//    This program is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
//    Contact: ph.prati@bluewin.ch

using System;
using System.Configuration;
using System.Windows.Forms;
using System.IO;
using System.Text;
using SdmxMl.Common;
using SdmxMl.Structure;
using SdmxMl.Manager;
using SdmxMl.HelpDoc;
using SdmxMl.GenericMetadata;
using SdmxMl.Multiplexor;
using SdmxMl.Panels;
using ActivityMgr.HGDE;
using System.Xml;
using SplashScreenTool;
using System.Collections.Generic;

namespace SAE
{
    /// <summary> SAE Main Form </summary>
    public partial class MainForm : Form
    {
        static MainForm()
        {
            Telerik.WinControls.RadTypeResolver.Instance.ResolveTypesInCurrentAssembly = true;
        }

        #region Splash screen

        private SplashScreen mSplashScreen;

        /// <summary>Hide splashscreen when fully loaded</summary>
        private void FormMain_Load(object sender, EventArgs e)
        {
            try
            {
                ReferenceManager.PlugInMgr = new PluginManager(ucPanelDetail.TabControlPlugin, treeManager);
                ReferenceManager.PlugInMgr.InitialLoadPlugin();

                if (mSplashScreen != null)
                    mSplashScreen.Hide();
            }
            catch (Exception ex)
            {
                if (mSplashScreen != null)
                    mSplashScreen.Hide();
                MessageBox.Show(this, ex.Message, "Plug-in Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

            }

            // Check Existence of required sub directories
            string appDir = System.IO.Path.GetDirectoryName(Application.ExecutablePath);
            if (Directory.Exists(appDir + "\\SDMX") == false ||
                Directory.Exists(appDir + "\\SMS") == false ||
                Directory.Exists(appDir + Path.DirectorySeparatorChar + PluginManager.PLUG_IN_SUBDIR_NAME) == false ||
                Directory.Exists(appDir + "\\XSD") == false)
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("CAUTION: some of the required child directories are missing.");
                sb.Append(Environment.NewLine);
                sb.Append("Please proceeds to a complete installation");
                sb.Append(Environment.NewLine);
                sb.Append("or download actual version at: www.sdmx.ch");

                MessageBox.Show(this, sb.ToString(), "Installation Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }

            // something to load
            string s = Environment.CommandLine;
            string[] arr = s.Split(' ');
            if (arr.Length > 1)
            {
                // assume file to load as arg 1
                try
                {
                    treeManager.LoadSdmxArtefact(arr[1], true, null);
                }
                catch { }
            }

        }
        #endregion

        #region Internal Members

        private TreeSdmxManager treeManager = null;
        private DlgRestSyntaxWizard dlfRestSyntax;

        #endregion

        #region Constructor

        public MainForm(SplashScreen splash)
        {
            mSplashScreen = splash;
            mSplashScreen.SetProgress("Initialize Components...", 0.1);
            InitializeComponent();

            try
            {
                mSplashScreen.SetProgress("Check Registry Access...", 0.5);
                InitSdmxTarget();

                InitTreeManager();

                mSplashScreen.SetProgress("Install Plug-in...", 0.8);
                InitNavigationManager();

                InitHelpDocMenu();

                InitSupportedLanguageList();

                treeView.SelectedNode = treeView.Nodes[0];

                InitCategoryEntries();

                // Change color of taskbar to signal SMS Domain (lemonChiffon)
                menuStripMain.BackColor = Mux.IsNewSmsRegistry ? System.Drawing.Color.LemonChiffon : System.Drawing.SystemColors.Control;
            }

            catch
            {
                if (mSplashScreen != null)
                    mSplashScreen.Hide();
                throw;

            }
        }

        private void InitCategoryEntries()
        {
            CategoryEntryManager catMgr = new CategoryEntryManager(harmonisationToolStripMenuItem);
        }

        /// <summary>
        /// SDMX-ML Schema version targeted (2.0 or 2.1)
        /// </summary>
        private void InitSdmxTarget()
        {
            toolStripButtonSdmxTarget.SelectedIndex = 0;
            toolStripButtonSdmxTarget.Enabled = false; // 2.1 not yet fully supported
        }

        /// <summary>Init manager for Tree and associated menu events</summary>
        private void InitTreeManager()
        {
            treeManager = new TreeSdmxManager();
            ReferenceManager.TreeMgr = treeManager;

            treeManager.TV = treeView;
            treeManager.StatusStripBar = this.statusStrip1;
            treeManager.PanelDetail = ucPanelDetail;

            // Repository Menu managment
            treeManager.RepositoryMenuMgr = new RepositoryMenuManager(treeView, ucPanelDetail);
            treeManager.RepositoryMenuMgr.assignMenuItems(getArtefactToolStripMenuItem,
                toolStripMenuItemSubmitArtefact, submitAggregatedArtefactsToRepositoryToolStripMenuItem,
                reserveArtefactMenuItem, repositorySourceToolStripMenuItem, updateTextsInFinalizedArtefactToolStripMenuItem, importLocalCopyToolStripMenuItem, subscribeToChangesToolStripMenuItem);
            treeManager.RepositoryMenuMgr.AssignButtons(toolStripButtonGetArtefact, toolStripButtonSubmit, toolStripButtonReserveArtefact);

            treeManager.ExportExcelToolStripMenuItem = exportExcelToolStripMenuItem;
            treeManager.CopyArtefactRefToolStripMenuItem = copyArtefactRefToolStripMenuItem;
            treeManager.ToolStripButtonSortList = this.toolStripButtonSort;
            treeManager.FindInAnnotationsToolStripMenuItem = findInAnnotationsToolStripMenuItem;

            treeManager.SaveSelectedArtefactToolStripMenuItem = saveSelectedArtefactToolStripMenuItem;
            treeManager.ToolStripButtonSaveArtefact = toolStripButtonSaveArtefact;
            treeManager.CsvDataToolStripMenuItem = cSVToolStripMenuItem1;
            treeManager.DSDWizardToolStripMenuItem = dSDWizardToolStripMenuItem;
            treeManager.AttachCsvToolStrips(cSVToolStripMenuItem, commaToolStripMenuItem, semicolumnToolStripMenuItem, tabulationToolStripMenuItem);
            treeManager.TreeSelect += new EventHandler(treeManager_TreeSelect);
        }

        private void treeManager_TreeSelect(object sender, EventArgs e)
        {
            versionsDifferencesToolStripMenuItem.Enabled = (treeView.SelectedNode != null && treeView.SelectedNode.Tag is CodeListType);
        }
        /// <summary>Init manager for navigating between loaded elements in tree</summary>
        private void InitNavigationManager()
        {
            NavigationManager.TreeSdmx = treeView;
            NavigationManager.RecordNavButtons(
                this.toolStripButtonNavBack,
                this.toolStripButtonNavFwd,
                this.toolStripButtonNavUp,
                this.toolStripComboBoxNavigate);
        }

        /// <summary>Help Menu Doc for SDMX and SMS</summary>
        private void InitHelpDocMenu()
        {
            DocMenuItems dmi = new DocMenuItems(this.documentationSDMXToolStripMenuItem);
            dmi.ConstructMenuItems();
            dmi = new DocMenuItems(this.documentationSMSToolStripMenuItem);
            dmi.ConstructMenuItems();
        }

        /// <summary> Combo with availables languages. Defaulted to 1st one </summary>
        private void InitSupportedLanguageList()
        {
            this.toolStripComboBoxLang.Items.Clear();
            foreach (string lang in LangSupport.SupportedLanguages)
                this.toolStripComboBoxLang.Items.Add(lang);
            this.toolStripComboBoxLang.SelectedIndex = 0;
        }

        #endregion

        #region Closing

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                // Raise event delegate if any
                if (ReferenceManager.TreeMgr.RaiseUserQuit())
                    e.Cancel = true;
                else
                {

                    // default confirmation
                    if (MessageBox.Show(this, "Do you really want to leave?", "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
                        e.Cancel = true;
                    else
                    {
                        treeView.DrawMode = TreeViewDrawMode.Normal; // quicker
                        ReferenceManager.TreeMgr.RaiseAppliClosing();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }
        #endregion

        #region Menu Events

        // Exit Application Event
        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        /// <summary> Menu Event: Open SDMX-ML file and load artefacts in treeview</summary>
        private void openFileToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                // Append if menu append or tool button
                bool append =
                    sender == appendArtefactToolStripMenuItem || sender == toolStripButtonOpenFile;

                if (openFileDlg.ShowDialog() == DialogResult.OK)
                {
                    foreach (string filename in openFileDlg.FileNames)
                    {
                        treeManager.LoadSdmxArtefact(filename, append, null);

                        // If many files, clear only at 1st one
                        append = true;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message + ex.StackTrace, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary> Menu Event: Update default language and Refresh display</summary>
        private void toolStripComboBoxLang_SelectedIndexChanged(object sender, EventArgs e)
        {

            treeManager.ChangeCurrentLanguage(toolStripComboBoxLang.SelectedIndex);
            treeView.Focus();
        }

        /// <summary> Menu Event: Raises About box</summary>
        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AboutBox about = new AboutBox();
            about.ShowDialog();

        }

        /// <summary> Menu Event: Expand or collapse tree under currently selected node</summary>
        private void toolStripTreeExpandFromLevel_Click(object sender, EventArgs e)
        {
            treeManager.ToggleFromSelectedLevel();
        }

        /// <summary> Menu Event: Save all artefacts in an SDMX-ML document</summary>
        /// <remarks> Dataset and Metadataset are not included as another scheme is required.</remarks>
        private void saveAllToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // All
            treeManager.SaveArtefact(null);
        }


        /// <summary> Menu Event: Raise Excel import dialog box</summary>
        private void excelToolStripMenuItem_Click(object sender, EventArgs e)
        {
            treeManager.ImportExcel();
        }

        /// <summary> Menu Event: Clear all tree content and associated artefact containers</summary>
        private void clearAllToolStripMenuItem_Click(object sender, EventArgs e)
        {
            treeManager.ClearAll(true);
        }

        /// <summary> SDMX Version to use for SDMX-ML XML serialisation </summary>
        /// <param name="sender"></param> <param name="e"></param>
        private void toolStripButtonSdmxTarget_SelectedIndexChanged(object sender, EventArgs e)
        {
            SdmxNamespaceManager.SdmxTarget = toolStripButtonSdmxTarget.SelectedIndex == 0 ?
                SdmxVersion.SDMX_20 : SdmxVersion.SDMX_21;
        }

        /// <summary>Menu Event: Append SDMX-ML artefact fetched from URI</summary>
        /// <param name="sender"></param> <param name="e"></param>
        private void appendFromUriToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DlgUri aDlg = new DlgUri(treeManager);
            aDlg.ShowDialog(this.menuStripMain);

        }

        /// <summary>Menu Event: Send feedback via mail </summary>
        /// <param name="sender"></param><param name="e"></param>
        private void sendFeedBackToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                if (ConfigurationManager.AppSettings["TinyRegistryVers"].ToString().Trim()[0] == '4')
                    System.Diagnostics.Process.Start("mailto:sdmx@nextsoft.ch?subject=SMS-SAE/Feedback");
                else
                    System.Diagnostics.Process.Start("mailto:sms@bfs.admin.ch?subject=SMS-SAE/Feedback");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

        #region Memory References

        private void memoryReferencesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            treeManager.MemoryRef();
        }

        private void locateUsageFromBaseToolStripMenuItem_Click(object sender, EventArgs e)
        {
            treeManager.RefererViaXmlBase();
        }
        #endregion


        #endregion

        #region SFSO HGDE Menu event

        /// <summary>
        /// Utility Menu for SFSO only (Municipalities hierarchy correspondances between two times)
        /// </summary>
        /// <param name="sender"></param> <param name="e"></param>
        private void hGDEToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                DlgHclCorr aDlg = new DlgHclCorr();
                aDlg.ShowDialog();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion

        private void ForceText(Category c)
        {
            if (c.Name.GetForLanguage("en") == string.Empty)
                c.Name.UpdateForLanguage("en", c.Name.GetForLanguage("fr"));
            foreach (Category cat in c.CategoryList)
                ForceText(cat);
        }
        private void pOPImportToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                using (new SdmxMl.Helper.CWaitCursor())
                {


                    DlgtargetRegistry aDlg = new DlgtargetRegistry();
                    if (aDlg.ShowDialog() == DialogResult.OK)
                    {
                        RegistryMultiplex RegMux = Mux.Instance as RegistryMultiplex;
                        if (RegMux != null)
                            RegMux.AllInOneRegistry(aDlg.RegistryUrn);
                    }

                    SdmxMl.Helper.ReferenceMaker maker = new SdmxMl.Helper.ReferenceMaker(@"C:\Artefacts_empty\");
                    maker.Scan();








                    //CodeListType clt = ReferenceManager.TreeSdmx.SelectedNode.Tag as CodeListType;
                    //if (clt != null)
                    //{
                    //    XmlDocument xDoc;
                    //    foreach (CodeType c in clt.CodeList)
                    //    {
                    //        string restBase = ConfigurationManager.AppSettings["RestEntryPoint"].ToString().Trim();

                    //        string rest =  c.Name.ToString().Length > 8 ? c.Name.ToString().Remove(0, 8) : c.Name.ToString(); // Remove restful

                    //        Uri uri = new Uri(restBase + "/" + rest);
                    //        System.Net.WebClient webclient = new System.Net.WebClient();
                    //        using (new SdmxMl.Helper.CWaitCursor())
                    //        {
                    //            SmManager sm = new SmManager();
                    //            xDoc = new XmlDocument();
                    //            if (rest.Trim() != "CDMGR")
                    //            {
                    //                xDoc.Load(webclient.OpenRead(uri));
                    //                sm.LoadSdmxDocument(null, true, xDoc);
                    //                if (sm.GetArtefactList(SdmxArtefactType.CodeLists).Count > 0)
                    //                {
                    //                    CodeListType cltRefered = sm.GetArtefactList(SdmxArtefactType.CodeLists)[0] as CodeListType;
                    //                    c.Name = cltRefered.Name.Clone();
                    //                }
                    //                else
                    //                {
                    //                    StructureSetType corresp = sm.GetArtefactList(SdmxArtefactType.StructureSets)[0] as StructureSetType;
                    //                    c.Name = corresp.Name.Clone();
                    //                }
                    //            }
                    //            c.AnnotationList.Clear();
                    //            Annotation a = new Annotation("REST_PARAM");
                    //            a.Title = rest;
                    //            c.AnnotationList.Add(a);
                    //        }
                    //    }
                    //}



                    /*
                    // Create codelist for mapping CdMgr ID to codelist urn
                    ArtefactList arl = ReferenceManager.GetArtefactList(SdmxArtefactType.CodeLists);
                    CodeListType clt = new CodeListType();
                    clt.AgencyId = "CH1_BURA";
                    clt.Id = "CL_MAP_CODEMGR";
                    clt.Name.UpdateForLanguage("en", "Mapping list between Codemanager classification ID and SDMX classification Rest urn");
                    foreach (Artefact a in arl)
                    {
                        CodeType c = new CodeType();
                        c.Id = a.Id.Substring(6);
                        string rest = "http://bfs015appt/Restful/codelist/CH1_BURA/" + a.Id + "/1.0";
                        c.Name.UpdateForLanguage("en", rest);
                        c.Uri = rest;
                        clt.CodeList.Add(c);
                    }
                    arl = ReferenceManager.GetArtefactList(SdmxArtefactType.HierarchicalCodelists);
                    foreach (Artefact a in arl)
                    {
                        CodeType c = new CodeType();
                        c.Id = a.Id.Substring(7);
                        string rest = "http://bfs015appt/Restful/hierarchicalcodelist/CH1_BURA/" + a.Id + "/1.0";
                        c.Name.UpdateForLanguage("en", rest);
                        c.Uri = rest;
                        clt.CodeList.Add(c);
                    }
                    SmManager sm = new SmManager();
                    sm.PutArtefact(SdmxArtefactType.CodeLists, clt);
                    object ob = NavigationManager.LoadFromSmManager(sm);
                    NavigationManager.RequestNavigation(ob);
                    */

                    // All codelist, change AgencyId and save

                    // All Hierarchy

                    //ConceptSchemeType cst = ReferenceManager.TreeSdmx.SelectedNode.Tag as ConceptSchemeType;
                    //if (cst != null)
                    //{
                    //    SdmxMl.SmsImportCfg.SakeVar sake = new SdmxMl.SmsImportCfg.SakeVar();
                    //    sake.ConstructCodes(cst);
                    //}

                    //SdmxMl.SmsImportCfg.SakeQuest quest = new SdmxMl.SmsImportCfg.SakeQuest();
                    //quest.ParseQuestFile(@"C:\Doc\SAKE\SAKE-Fragebogen 2013_(D_F_I_E).xls");


                    /*
                     if (ReferenceManager.TreeSdmx.SelectedNode == null)
                        throw new ApplicationException("Nothing Selected in Tree !");
                     ConceptSchemeType cst = ReferenceManager.TreeSdmx.SelectedNode.Tag as ConceptSchemeType;

                     CodeListType cl = ReferenceManager.TreeSdmx.SelectedNode.Tag as CodeListType;

                     if (cl != null)
                     {
                         foreach (CodeType code in cl.CodeList)
                         {
                             Annotation a = code.AnnotationList[0];
                             a.Type = "ABBREV";
                         }
                     }

                   if (cst != null)
                   {
                       foreach (ConceptType c in cst.ConceptList)
                       {
                         //  ForceText(c);
                           
                           Annotation a = c.AnnotationList.GetAnnotationType("INDIC_SUP");
                           if (a != null)
                           {
                               a.Title = a.Text.GetForLanguage("fr").Trim('-');
                               a.Text.UpdateDefaultText(string.Empty);
                           }

                           a = c.AnnotationList.GetAnnotationType("GROUP");
                           if (a != null)
                           {
                               a.Title = a.Text.GetForLanguage("fr");
                               a.Text.UpdateDefaultText(string.Empty);
                           }
                            
                           
                           Annotation a = c.AnnotationList.GetAnnotationType("VAGUE");
                           if (a != null)
                               a.Text.UpdateDefaultText(string.Empty);

                       }
                   }
                     * */

                    /*
                    SdmxMl.SmsImportCfg.SakeVar sake = new SdmxMl.SmsImportCfg.SakeVar();
                  //  sake.ConstructVars();
                    ConceptSchemeType cst = ReferenceManager.TreeSdmx.SelectedNode.Tag as ConceptSchemeType;
                    if (cst != null)
                    {
                        //VariablesESPA2012_MetastatNew.xls
                        sake.ConstructAnnot(cst, @"C:\Doc\SAKE\VariablesESPA2012_Metastat_v397.xls");
                       // sake.ConstructCodes(cst);
                        ArtefactManager am = ReferenceManager.TreeSdmx.SelectedNode.Parent.Tag as ArtefactManager;
                        am.ArtefactList.Remove(cst);
                        ReferenceManager.TreeSdmx.SelectedNode.Parent.Nodes.Remove(ReferenceManager.TreeSdmx.SelectedNode);
                        object ob = NavigationManager.LoadFromSmManager(sake.sm);
                        NavigationManager.RequestNavigation(ob);
                    }

                    */

                    // toolStripButton4_Click(sender, e);

                    // Mux.Instance.AllInOneRegistry("http://localhost:1840/TinyRegistry/Repository.asmx");

                    /* ESS migration
                     * 
                     if (ReferenceManager.TreeSdmx.SelectedNode == null)
                        throw new ApplicationException("Nothing Selected in Tree !");
                   ConceptSchemeType cst = ReferenceManager.TreeSdmx.SelectedNode.Tag as ConceptSchemeType;
                   if (cst != null)
                   {
                       EssConcepts ess = new EssConcepts(@"C:\Doc\ESS\ESS07_labels");
                       ess.CreateForlang("de");
                       ess.UpdateForLang("fr");
                       ess.UpdateForLang("it");

                       ess.SyncAnnotations(cst);

                       // now sort concepts
                   //    ess.CsScheme.ConceptList.Sort(delegate(ISdmxHierarchyListItem p1, ISdmxHierarchyListItem p2)
                   //    { return p1.Id.CompareTo(p2.Id); });

                       SmManager sm = new SmManager();
                       sm.PutArtefact(SdmxArtefactType.Concepts, ess.CsScheme);
                       XmlDocument xDoc = sm.GetAsDocument();

                       treeManager.LoadSdmxArtefact(null, true, xDoc);

                  }
                     * */
                    /*

                    if (ReferenceManager.TreeSdmx.SelectedNode == null)
                        throw new ApplicationException("Nothing Selected in Tree !");

                    // Is an artefact selected in tree
                    HierarchicalCodelistType hcl = ReferenceManager.TreeSdmx.SelectedNode.Tag as HierarchicalCodelistType;
                    if (hcl == null || hcl.HierarchyList.Count == 0)
                        throw new ApplicationException("No valid hierarchy selected in Tree!");

                    SdmxMl.Excel.ImportHierarchyValidity ihv = new SdmxMl.Excel.ImportHierarchyValidity();
                    ihv.UpdateHierarchy(hcl.HierarchyList[0], @"c:\doc\Copie de matg_org.xls");
                     * */
                    /*
                    SdmxMl.Excel.POP_Import pop = new SdmxMl.Excel.POP_Import();
                    SmManager sm = pop.LoadToSdmx();
                    XmlDocument xDoc = sm.GetAsDocument();
                    if (xDoc != null)
                        treeManager.LoadSdmxArtefact(null, true, xDoc);
                     * */

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void fACTAndDIMsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                if (ReferenceManager.TreeSdmx.SelectedNode == null)
                    throw new ApplicationException("Nothing Selected in Tree !");

                // Is an artefact selected in tree
                Artefact a = ReferenceManager.TreeSdmx.SelectedNode.Tag as Artefact;
                if (a == null)
                    throw new ApplicationException("No Artefact selected in Tree!");

                // Is artefact of supported types
                if (a is KeyFamilyType || a is HierarchicalCodelistType || a is CodeListType)
                {
                    SmManager sm = ReferenceManager.GetSmContainerImage();

                    SdmxMl.Panels.DlgFactAndDim aDlg = new SdmxMl.Panels.DlgFactAndDim(sm, a);
                    aDlg.ShowDialog(this);
                }
                else
                {
                    throw new ApplicationException("Invalid artefact type selected!" + Environment.NewLine +
                    "Should be: HierarchicalCodelist or Codelist or DSD");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "FACT & DIMs", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }




        public static ConceptSchemeType cstMark = null;

        private void CatRecurse(CategoryList itemList, List<Category> catList)
        {
            foreach (Category item in itemList)
            {
                Annotation a = item.AnnotationList.GetAnnotationType("SMS_TYPE");
                if (a != null && a.Text.ToString() == "A")
                    catList.Add(item);

                CatRecurse(item.CategoryList, catList);
            }
        }

        private void MarkConceptToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //if (treeView.SelectedNode != null)
            //{
            //    CategorySchemeType cat = treeView.SelectedNode.Tag as CategorySchemeType;
            //    if (cat != null)
            //    {
            //        List<Category> catList = new List<Category>();
            //        CatRecurse(cat.CategoryList, catList);

            //        foreach (Category c in catList)
            //            cat.CategoryList.RemoveHierarchicalItem(c);

            //    }
            //}

            if (treeView.SelectedNode != null)
            {
                ConceptSchemeType cst = treeView.SelectedNode.Tag as ConceptSchemeType;
                cstMark = cst;
            }

        }

        private void PlaceConceptToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (treeView.SelectedNode != null)
            {
                ConceptSchemeType clt = treeView.SelectedNode.Tag as ConceptSchemeType;
                if (clt != null && cstMark != null)
                {
                    CreateFlags(treeView.SelectedNode.Nodes[0], clt, cstMark);
                }
            }
        }

        private void RecurseConcepts(TreeNode parent, ConceptSchemeType cstFlags, ConceptSchemeType cstMark)
        {
            ConceptType c = parent.Tag as ConceptType;
            if (c != null)
            {
                //is it leaf
                bool leaf = parent.Nodes.Count == 0;

                // Duplicate
                cstFlags.ConceptList.Add(c);

                // Add flag if leaf
                if (leaf)
                {

                    ISdmxHierarchyListItem item = cstMark.ConceptList.LocateItem(c.Id); // + "_F");
                    if (item != null)
                    {
                        ConceptType cf = new ConceptType();
                        cf.Id = item.Id + "_F";
                        cf.Name.UpdateDefaultText("Flag for " + c.Id);
                        cf.Parent = c.Parent;
                        ConceptType cfOld = item as ConceptType;
                        //    cf.TextFormat = new TextFormatType(cfOld.TextFormat);
                        //    cf.CoreRepresentation.Id = cfOld.CoreRepresentation.Id;
                        //     cf.CoreRepresentation.AgencyId = cfOld.CoreRepresentation.AgencyId;
                        //     cf.CoreRepresentation.Version = cfOld.CoreRepresentation.Version;
                        cstFlags.ConceptList.Add(cf);
                    }
                }
            }

            //now parent collection
            foreach (TreeNode node in parent.Nodes)
                RecurseConcepts(node, cstFlags, cstMark);
        }



        private void CreateFlags(TreeNode root, ConceptSchemeType cst, ConceptSchemeType cstMark)
        {
            //Create new conceptscheme for flags
            ConceptSchemeType cstFlags = new ConceptSchemeType();
            cstFlags.AgencyId = cst.AgencyId;
            cstFlags.Id = cst.Id;
            cstFlags.Version = "1.1";
            foreach (string lg in LangSupport.SupportedLanguages)
            {
                cstFlags.Name.UpdateForLanguage(lg, cst.Name.GetForLanguage(lg));
                cstFlags.Description.UpdateForLanguage(lg, cst.Description.GetForLanguage(lg));
            }

            // Duplicate concepts hierarchy. Add "_F" to Leafs concept ID, copy name
            // Work from treeview representation
            cst.ConceptList.HasHierarchy = true;

            // Recurse Concepts part of tree representation
            RecurseConcepts(root, cstFlags, cstMark);

            //Persist new concept scheme
            SmManager sm = new SmManager();
            sm.PutArtefact(SdmxArtefactType.Concepts, cstFlags);

            XmlDocument xDoc = new XmlDocument();
            xDoc = sm.GetAsDocument();
            xDoc.Save("C:\\" + cstFlags.FullIdent + ".xml");


        }

        private void fillerToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                using (new SdmxMl.Helper.CWaitCursor())
                {
                    //GroupMetaTransfer groupTfer = new GroupMetaTransfer(@"C:\ArtefactsSDMX\GroupExport", "CH1_RN", Mux.Instance);
                    //groupTfer.LoadDirInfoImages();


                    SdmxMl.SmsImportCfg.SakeQuest quest = new SdmxMl.SmsImportCfg.SakeQuest();
                    quest.ParseQuestFile(@"C:\Doc\SAKE\sake_QuestAll.xls");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "Flow", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }


            /* // Fill code with padding
            if (treeView.SelectedNode != null && treeView.SelectedNode.Tag is CodeListType)
            {
                CodeListType clt = treeView.SelectedNode.Tag as CodeListType;
                char padChar = '0';
                int normSize = 4;
                foreach (TreeNode nd in treeView.SelectedNode.Nodes[0].Nodes)
                {
                    CodeType c = nd.Tag as CodeType;
                    if (c != null && c.Id.Length < normSize)
                    {
                        StringBuilder sb = new StringBuilder();
                        for (int i = 0; i < normSize - c.Id.Length; ++i )
                            sb.Append(padChar);
                        sb.Append(c.Id);
                        c.Id = sb.ToString();
                        nd.Text = c.ToString();
                    }
                }
            }
              * */

        }

        private void genConceptFlagsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // current must be the flag sample
            if (treeView.SelectedNode != null && treeView.SelectedNode.Tag is ConceptType)
            {
                ConceptType cSource = treeView.SelectedNode.Tag as ConceptType;
                //get scheme
                ConceptSchemeType cst = SdmxMl.Helper.TreeHelper.GetParentArtefact(treeView.SelectedNode) as ConceptSchemeType;
                cst.ConceptList.HasHierarchy = true;

                TreeNode conceptSchemeNode = SdmxMl.Helper.TreeHelper.GetParentArtefactNode(treeView.SelectedNode);
                if (cst != null && conceptSchemeNode != null)
                {
                    // recurse to add flags
                    foreach (TreeNode node in conceptSchemeNode.Nodes)
                        RecurseForFlag(node, cSource, cst);

                    // Now tree refresh
                    treeView.BeginUpdate();
                    conceptSchemeNode.Nodes[0].Nodes.Clear();
                    cst.ConceptList.FillTree(conceptSchemeNode.Nodes[0]);
                    treeView.EndUpdate();
                }
            }


        }

        private void RecurseForFlag(TreeNode node, ConceptType cSource, ConceptSchemeType cst)
        {
            ConceptType c = node.Tag as ConceptType;
            if (c != null && c != cSource)
            {
                //is it leaf
                bool leaf = node.Nodes.Count == 0;
                // if not already a flag, create one as child
                if (c.Id.EndsWith("_F") == false)
                {
                    ConceptType cf = new ConceptType();
                    cf.Id = c.Id + "_F";
                    cf.Name.UpdateDefaultText("Flag for " + c.Id);
                    cf.Parent = c.Id;
                    cf.TextFormat = new TextFormatType(cSource.TextFormat);
                    cf.CoreRepresentation.Id = cSource.CoreRepresentation.Id;
                    cf.CoreRepresentation.AgencyId = cSource.CoreRepresentation.AgencyId;
                    cf.CoreRepresentation.Version = cSource.CoreRepresentation.Version;
                    cf.AnnotationList = cSource.AnnotationList.Clone();
                    cst.ConceptList.Add(cf);
                }
            }

            foreach (TreeNode n in node.Nodes)
                RecurseForFlag(n, cSource, cst);

        }

        private void generateFlowToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // Si DSD ou MSD couramment sélectionné, génèrer artefact flow correspondant
            if (treeView.SelectedNode != null && treeView.SelectedNode.Tag is Artefact)
            {
                try
                {

                    MetadataSetType gmd = treeView.SelectedNode.Tag as MetadataSetType;
                    KeyFamilyType dsd = treeView.SelectedNode.Tag as KeyFamilyType;

                    if (gmd != null)
                    {
                        MetadataflowType mf = new MetadataflowType();
                        // ID as MSD, but remove MSD_ if any and replace with MF_
                        // Agency same as 
                        string id = gmd.Id;
                        if (id.StartsWith("GMD_"))
                            id = gmd.Id.Substring(4);
                        mf.Id = "MF_" + id;
                        mf.AgencyId = gmd.AgencyId;
                        mf.Version = gmd.Version;
                        mf.Name = gmd.Name.Clone();
                        mf.MetadataStructureRef.Id = gmd.MetadataStructureRef.Id;
                        mf.MetadataStructureRef.AgencyId = gmd.MetadataStructureRef.AgencyId;
                        mf.MetadataStructureRef.Version = gmd.MetadataStructureRef.Version;

                        mf.Uri = UrnManager.FullIdToUrn(SdmxArtefactType.MetadataSet, gmd.FullIdent);

                        if (ReferenceManager.LocateArtefact(SdmxArtefactType.Metadataflows, mf) != null)
                            MessageBox.Show("Metadataflow already present in main tree!", "Info", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        else
                        {
                            // Add in tree
                            foreach (TreeNode node in ReferenceManager.TreeSdmx.Nodes)
                            {
                                ArtefactManager am = node.Tag as ArtefactManager;
                                if (am != null && am.ArtefactType == SdmxArtefactType.Metadataflows)
                                {
                                    am.ArtefactList.Add(mf);
                                    mf.FillNode(node);
                                    ReferenceManager.TreeSdmx.SelectedNode = node.LastNode;
                                    node.LastNode.Expand();
                                    break;
                                }
                            }

                        }
                    }
                    else if (dsd != null)
                    {
                        // ID as DSD, but remove DSD_ if any and replace with MF_
                        // Agency same as DSD

                        DataflowType df = new DataflowType();
                        string id = dsd.Id;
                        if (id.StartsWith("DSD_"))
                            id = dsd.Id.Substring(4);
                        df.Id = "DF_" + id;
                        df.AgencyId = dsd.AgencyId;
                        df.Version = dsd.Version;
                        df.Name = dsd.Name.Clone();
                        df.KeyFamilyRef.Id = dsd.Id;
                        df.KeyFamilyRef.AgencyId = dsd.AgencyId;
                        df.KeyFamilyRef.Version = dsd.Version;

                        if (ReferenceManager.LocateArtefact(SdmxArtefactType.Dataflows, df) != null)
                            MessageBox.Show("Dataflow already present in main tree!", "Info", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        else
                        {
                            // Add in tree
                            foreach (TreeNode node in ReferenceManager.TreeSdmx.Nodes)
                            {
                                ArtefactManager am = node.Tag as ArtefactManager;
                                if (am != null && am.ArtefactType == SdmxArtefactType.Dataflows)
                                {
                                    am.ArtefactList.Add(df);
                                    df.FillNode(node);
                                    ReferenceManager.TreeSdmx.SelectedNode = node.LastNode;
                                    node.LastNode.Expand();
                                    break;
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(this, ex.Message, "Flow", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }

        }

        private MetadataSetType metaSet = null;
        private MetadataStructureDefinitionType msd = null;
        private ReportStructureType report = null;

        private void toolStripButton4_Click(object sender, EventArgs e)
        {

        }

        private void SetRepAttValue(AttributeValueSetType at, string conceptId, MultiLang ml)
        {
            ReportedAttributeType ra = at.ReportedAttributeList.GetReportedAttributeOfConcept(conceptId);
            if (ra != null)
                ra.Value = ml == null ? new MultiLang() : ml;
        }

        private void FillFromContactType(ContactType ct, string GrpId)
        {
            string userID = ct.Id;
            if (string.IsNullOrEmpty(userID) == false)
            {
                AttributeValueSetType suiviAt = new AttributeValueSetType(msd, report, metaSet);
                suiviAt.TargetValuesTypeList.SetComponentValue("UID", userID);
                SetRepAttValue(suiviAt, "UNAME", ct.Name.Clone());
                string email = ct.ContactInfo.EmailList.Count == 0 ? string.Empty : ct.ContactInfo.EmailList[0];
                SetRepAttValue(suiviAt, "UEMAIL", new MultiLang(email));
                string phone = ct.ContactInfo.TelephoneList.Count == 0 ? string.Empty : ct.ContactInfo.TelephoneList[0];
                SetRepAttValue(suiviAt, "UPHONE", new MultiLang(phone));
                SetRepAttValue(suiviAt, "SAE_VERS", new MultiLang("0_98"));
                SetRepAttValue(suiviAt, "SUBSCR_SAE", new MultiLang("0"));

                // For each Group
                SetRepAttValue(suiviAt, "UGRP_ID", new MultiLang(GrpId));
                SetRepAttValue(suiviAt, "UROLE", new MultiLang(ct.Role.Clone()));
                metaSet.AttributeValueSetList.Add(suiviAt);
            }
        }


        #region NRME remove internationalisation

        /// <summary>
        /// On metadataser report, remove multilingual and keeps only currently selected language
        /// (NRME support)
        /// </summary>
        /// <param name="sender"></param> <param name="e"></param>
        private void removeInternationalizationToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                if (treeView.SelectedNode != null && treeView.SelectedNode.Tag is MetadataSetType)
                {
                    MetadataSetType meta = treeView.SelectedNode.Tag as MetadataSetType;
                    foreach (AttributeValueSetType atv in meta.AttributeValueSetList)
                    {
                        removeInternationalisationAtLevel(atv.ReportedAttributeList);
                    }

                    MessageBox.Show(this, "Internationalisation suppressed.", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }

        private void removeInternationalisationAtLevel(ReportedAttributeTypeList ratl)
        {
            foreach (ReportedAttributeType r in ratl)
            {
                foreach (string lg in LangSupport.SupportedLanguages)
                {
                    if (lg != LangSupport.CurLang)
                        r.InternationalizedValue.UpdateForLanguage(lg, string.Empty);
                }

                removeInternationalisationAtLevel(r.ReportedAttributeList);
            }
        }
        #endregion


        /// <summary>
        /// Helper for generation of syntax for queriing REST service 
        /// (Official entry point for consulting Metadata via web service.)
        /// </summary>
        /// <param name="sender"></param> <param name="e"></param>
        private void RestSyntaxWizardToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                if (dlfRestSyntax == null)
                {
                    dlfRestSyntax = new DlgRestSyntaxWizard();
                    dlfRestSyntax.FormClosed += new FormClosedEventHandler(dlfRestSyntax_FormClosed);
                }
                dlfRestSyntax.WindowState = FormWindowState.Normal;
                dlfRestSyntax.Focus();
                dlfRestSyntax.Show();

            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }

        void dlfRestSyntax_FormClosed(object sender, FormClosedEventArgs e)
        {
            dlfRestSyntax = null;
        }

        private void diffToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                SdmxDiff.DlgDiff aDlg = new SdmxDiff.DlgDiff();
                aDlg.Show();
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void ucSearchTree1_Load(object sender, EventArgs e)
        {
        }

        private void checkArtefactToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                Artefact a = null;
                ArtefactManager arm = null;
                treeManager.RepositoryMenuMgr.CheckArtefact(out a, out arm);
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }

        private void filesDifferencesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                string appDir = System.IO.Path.GetDirectoryName(Application.ExecutablePath);
                appDir += System.IO.Path.DirectorySeparatorChar + "officediff.exe";
                System.Diagnostics.Process.Start(appDir);
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }


    }

}
